package com.fa4j.system.notice.service.impl;

import com.fa4j.common.base.exception.CommonRequestError;
import com.fa4j.common.base.model.RemoveCmd;
import com.fa4j.system.notice.convert.NoticeConverter;
import com.fa4j.system.notice.model.Notice;
import com.fa4j.system.notice.model.NoticeCreateCmd;
import com.fa4j.system.notice.model.NoticeModifyStateCmd;
import com.fa4j.system.notice.model.NoticeState;
import com.fa4j.system.notice.repository.NoticeRepository;
import com.fa4j.system.notice.service.NoticeService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.Objects;

/**
 * 系统通知 服务接口实现
 *
 * @since 2025-07-01 08:47:55
 */
@Slf4j
@Service
@Validated
@RequiredArgsConstructor
public class NoticeServiceImpl implements NoticeService {

    private final NoticeRepository noticeRepository;
    private final NoticeConverter noticeConverter;

    /**
     * 新增系统通知
     *
     * @param cmd 新增参数
     * @return 系统通知
     */
    @Override
    public Notice create(@Valid NoticeCreateCmd cmd) {
        Notice entity = noticeConverter.toEntity(cmd);
        entity.setState(NoticeState.UNREAD);
        noticeRepository.create(entity);
        return entity;
    }

    /**
     * 删除系统通知
     *
     * @param cmd 删除参数
     * @return 系统通知
     */
    @Override
    public Notice remove(@Valid RemoveCmd<Long> cmd) {
        Notice entity = noticeRepository.findById(cmd.getId())
                .orElseThrow(() -> CommonRequestError.NOT_FOUND.build("系统通知"));
        if (!Objects.equals(entity.getAccountId(), cmd.getOperatorId())) {
            // 只能删除账号自己的消息,否则无权限
            throw CommonRequestError.FORBIDDEN.build();
        }
        entity.setOperatorId(cmd.getOperatorId());
        noticeRepository.remove(entity);
        return entity;
    }


    /**
     * 编辑系统通知参数
     *
     * @param cmd 参数
     * @return 系统通知
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Notice modifyState(NoticeModifyStateCmd cmd) {
        Notice entity = noticeRepository.findById(cmd.getId())
                .orElseThrow(() -> CommonRequestError.NOT_FOUND.build("系统通知"));
        if (!Objects.equals(entity.getAccountId(), cmd.getOperatorId())) {
            // 只能删除账号自己的消息,否则无权限
            throw CommonRequestError.FORBIDDEN.build();
        }
        entity.setState(cmd.getState());
        entity.setOperatorId(cmd.getOperatorId());
        noticeRepository.modify(entity);
        return entity;
    }
}




